// time_advance.cpp
// this program can be written easier with boost ptime_facet.
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>

#include <boost/date_time/posix_time/posix_time.hpp>

#include "from_yyyyddd_string.h"

using namespace std;
using namespace boost::posix_time;
using namespace boost::gregorian;

int main(int argc, char *argv[])
{
	ptime start_t;
	ptime end_t;
	time_duration duration;
	
	if(argc < 3)
	{
		cout << "Usage: " << endl;
		cout << "    hour_advance 2009153 110000 24" << endl;
		cout << "    hour_advance 20090325 230000 10d" << endl;
		cout << "    hour_advance 20090630120000 60m" << endl;
		cout << "    hour_advance 20091231T235959 3600s" << endl;
	}
	else
	{
		string duration_str = argv[argc - 1];

		stringstream ss;
		long duration_num;
		ss << duration_str;
		ss >> duration_num;
		switch(duration_str[duration_str.length() - 1])
		{
		case 'd':
			duration = hours(duration_num * 24);
			break;
		case 'm':
			duration = minutes(duration_num);
			break;
		case 's':
			duration = seconds(duration_num);
			break;
		default:
			duration = hours(duration_num);
		}
	}

	if(argc == 3)
	{
		string d_t = argv[1];
		if(d_t.length() == 14) //iso string without 'T', yyyymmddhhmmss
		{
			d_t.insert(8, 1, 'T');
			start_t = from_iso_string(d_t);
			end_t = start_t + duration;
			string res = to_iso_string(end_t);
			res.erase(8, 1);
			cout << res << endl;
			return 0;
		}
		else if(d_t.length() == 15) // with 'T', yyyymmddThhmmss
		{
			start_t = from_iso_string(d_t);
			end_t = start_t + duration;
			cout << to_iso_string(end_t) << endl;
			return 0;
		}
		else
		{
			return 0;
		}
	}
	if(argc == 4) //date time seperated by whitespace
	{
		string y_d = argv[1];
		string hhmmss = argv[2];

		if(y_d.length() == 7) //yyyyddd
		{
			date start_date = from_yyyyddd_string(y_d);
			start_t = from_iso_string(to_iso_string(start_date) + 'T' + hhmmss);
			end_t = start_t + duration;
			cout << end_t.date().year() << setw(3) << setfill('0') << end_t.date().day_of_year() << " " << to_iso_string(end_t.time_of_day()) << endl;
			return 0;
		}
		else if(y_d.length() == 8) //yyyymmdd
		{
			start_t = from_iso_string(y_d + 'T' + hhmmss);
			end_t = start_t + duration;
			string res = to_iso_string(end_t);
			res[8] = ' ';
			cout << res << endl;
			return 0;
		}
		else
		{
			return 0;
		}
	}
	else
	{
		return 0;
	}
}
